home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_13_08 / gottner / hashmap.cxx < prev    next >
Encoding:
C/C++ Source or Header  |  1995-06-04  |  1.8 KB  |  86 lines

  1. /*----------------------------------------*
  2.  * hashhmap.cxx --
  3.  *    Implementation of the VPmap class.
  4.  */
  5. #include <stdlib.h>
  6. #include "hashmap.h"
  7.  
  8. /*----------------------------------------*
  9.  * convenient macros
  10.  */
  11. #define ELEMENTS(array) \
  12.         (sizeof(array) / sizeof(array[0]))
  13.  
  14. #define EACHELEM(x, array, size) \
  15.         x = &(array)[size]; \
  16.         x-- > (array);
  17.  
  18.  
  19. VPmap::VPmap(
  20.          size_t             buckets,
  21.          KeyHashProc        key_hash,
  22.          KeyCompareEqProc   key_cmp,
  23.          KeyValCreateProc   K_V_C,
  24.          KeyValDestroyProc  K_V_D)
  25. {
  26.     hash               = key_hash;
  27.     isEqual            = key_cmp;
  28.     CreateKeyAndValue  = K_V_C;
  29.     DestroyKeyAndValue = K_V_D;
  30.     hashsize           = buckets;
  31.  
  32.     VPAssoc **ptr;
  33.     keys = new VPAssoc *[hashsize];
  34.     for (EACHELEM(ptr, keys, hashsize))
  35.         *ptr = NULL;
  36. }
  37.  
  38.  
  39.  
  40. VPmap::~VPmap()
  41. {
  42.     VPAssoc **list;
  43.  
  44.     for (EACHELEM(list, keys, hashsize))
  45.         while (*list) {
  46.             VPAssoc *item  = *list;
  47.             *list = item->next;
  48.  
  49.             DestroyKeyAndValue(item->key, item->value);
  50.             delete item;
  51.         }
  52.  
  53.     delete[] keys;
  54. }
  55.  
  56.  
  57.  
  58. void VPmap::apply(VPiterProc proc, void *data)
  59. {
  60.     VPAssoc **list, *item;
  61.  
  62.     for (EACHELEM(list, keys, hashsize))
  63.         for (item = *list; item != NULL; item = item->next)
  64.             (*proc)(item->key, item->value, data);
  65. }
  66.  
  67.  
  68.  
  69. void *VPmap::index(const void *theKey)
  70. {
  71.     VPAssoc *item, **list = &keys[hash(theKey) % hashsize];
  72.  
  73.     for (item = *list; item != NULL; item = item->next)
  74.         if (isEqual(theKey, item->key))
  75.             return item->value;
  76.  
  77.     VPAssoc *n = new VPAssoc;
  78.     CreateKeyAndValue(this, theKey, n->key, n->value);
  79.     n->next = *list;
  80.     *list = n;
  81.  
  82.     return n->value;
  83. }
  84.  
  85.  
  86.